<template>
  <view>
    <uni-list>
      <block v-for="(item, index) in authorities" :key="index">
        <template v-if="item.isActive !== false">
          <uni-list-item
            :thumb="item.userImage"
            thumb-size="lg"
            :title="item.userName"
          >
            <template slot="footer">
              <button class="footer-remove-btn" @click="remove(item, index)">
                删除
              </button>
            </template></uni-list-item
          >
        </template>
      </block>
    </uni-list>
    <view class="null-content"></view>
    <view class="footer-btn" v-if="isShowSaveBtn">
      <view class="footer-mark"
        >注意：添加权限范围，请点击下面的保存按钮，否则不生效</view
      >
      <view class="to-add" @tap="toSave">保存</view>
    </view>
    <view class="footer-btn" v-else>
      <view class="to-add" @tap="toAuthority">添加权限范围</view>
    </view>
  </view>
</template>

<script>
import uniList from "../../components/uni-list/uni-list";
import uniListItem from "../../components/uni-list-item/uni-list-item";
import {
  findPowerBycode,
  delectPower,
  savePower,
  savePowerSource,
} from "../../common/service.js";

export default {
  components: {
    uniList,
    uniListItem,
  },
  data() {
    return {
      loginInfo: {},
      isShowSaveBtn: false,
      authorities: [],
      callbackItems: [], // 上一页带回的已选项
    };
  },
  onLoad(e) {
    if (e.loginInfo) {
      this.loginInfo = JSON.parse(e.loginInfo);
      this.getAuthorities();
    }
  },
  onShow() {
    if (this.callbackItems.length > 0) {
      this.isShowSaveBtn = true;
    }
    if (
      this.loginInfo &&
      this.loginInfo.parentUserId &&
      this.loginInfo.powerModule &&
      this.loginInfo.toPowerId
    ) {
      this.loginInfo = this.loginInfo;
      this.getAuthorities();
    }
  },
  methods: {
    getAuthorities() {
      uni.showLoading({
        title: "加载中",
      });
      findPowerBycode(
        {
          userName: this.loginInfo.toPowerId,
          powerModule: this.loginInfo.powerModule,
          parentUserId: this.loginInfo.parentUserId, // 父级授权人
        },
        (res) => {
          uni.hideLoading();
          if (res && res.data && res.data.code == 200) {
            let arr = [];
            if (res.data.dept && res.data.dept.length > 0) {
              let list = res.data.dept;
              if (list.length > 0) {
                for (let i = 0; i < list.length; i++) {
                  arr = arr.concat(this.__format(list[i]));
                }
              }
            }
            if (res.data.user && res.data.user.length > 0) {
              let list = res.data.user;
              if (list.length > 0) {
                for (let i = 0; i < list.length; i++) {
                  arr = arr.concat(this.__formatStaff(list[i]));
                }
              }
            }
            this.authorities = arr;

            // 如果有返回数据
            if (this.callbackItems && this.callbackItems.length > 0) {
              const values = [];
              this.callbackItems.map((s) => {
                values.push(s.userId);
              });
              for (var i = 0, lenI = this.authorities.length; i < lenI; ++i) {
                const item = this.authorities[i];
                if (values.includes(item.userId)) {
                  this.authorities[i].isActive = true;
                } else {
                  this.authorities[i].isActive = false;
                }
              }
              const newAddStaff = this.unique(
                this.callbackItems.concat(this.authorities)
              );
              this.authorities = newAddStaff;
            }
          } else {
            uni.showToast({
              title: "查询权限失败",
              duration: 2000,
            });
          }
        },
        (err) => {
          uni.showToast({
            title: "查询权限失败",
            duration: 2000,
          });
        }
      );
    },
    /**
     * 根据 id 进行数组去重
     * @param {array} origin 原始数组
     */
    unique(origin) {
      let temp = {};
      return origin
        .reverse()
        .filter((item) =>
          item.userId in temp ? false : (temp[item.userId] = true)
        );
    },
    remove(item, index) {
      let self = this;
      if (self.isShowSaveBtn) {
        // 已选择完权限，保存
        if (self.authorities.length > 0) {
          let deleteIndex = self.authorities.findIndex(
            (auth) => auth.userId === item.userId
          );
          if (self.authorities[deleteIndex].hasOwnProperty("isActive")) {
            self.authorities[deleteIndex].isActive = false;
            self.authorities.splice(deleteIndex, 0);
          } else {
            self.authorities.splice(deleteIndex, 1);
          }
        }
      } else {
        uni.showModal({
          title: "提示",
          content: `确认删除 ${item.userName} 此权限吗`,
          success: function (res) {
            if (res.confirm) {
              console.log("用户点击确定");
              uni.showLoading({
                title: "删除中",
              });
              const data = {
                parentUserId: self.loginInfo.parentUserId, // 父级授权人
                toPowerId: self.loginInfo.toPowerId, //   授权对象
                powerDeptId: "", //被授权的部门id（删除用户权限此项传空）
                powerUserId: "", // 被授权的对象id（删除部门权限此项传空）
                powerModule: self.loginInfo.powerModule, // 权限模块（巡店固定值：XD_RESULT）
              };
              if (item.type == "department") {
                data.powerDeptId = item.userId;
              } else if (item.type == "employee") {
                data.powerUserId = item.userId;
              }
              delectPower(
                data,
                (res) => {
                  if (res && res.data && res.data.code == 200) {
                    uni.showToast({
                      title: "删除成功",
                      duration: 2000,
                    });
                    setTimeout(() => {
                      self.authorities.splice(index, 1);
                      console.log('🍌', self.loginInfo.toPowerId);
                      savePowerSource(
                        { userNames: self.loginInfo.toPowerId },
                        (res) => {
                          console.log(res.data);
                        },
                        (err) => {
                          console.log(err);
                        }
                      );
                    }, 2000);
                  } else {
                    uni.showToast({
                      title: "删除失败",
                      duration: 2000,
                    });
                  }
                },
                (err) => {
                  uni.showToast({
                    title: "删除失败",
                    duration: 2000,
                  });
                }
              );
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      }
    },
    toAuthority() {
      const isSelectStaff = false;
      const title = "权限范围";
      const isJump = false;
      uni.navigateTo({
        url:
          "../selectStaff/selectStaff?isSelectStaff=" +
          JSON.stringify(isSelectStaff) +
          "&postStaff=" +
          JSON.stringify(this.authorities) +
          "&title=" +
          JSON.stringify(title) +
          "&isJump=" +
          JSON.stringify(isJump) +
          "&loginInfo=" +
          JSON.stringify(this.loginInfo),
      });
    },
    // 格式转化
    __format(item) {
      let arr = [];
      if (item.toSysDepts && item.toSysDepts.length > 0) {
        item.toSysDepts.forEach((dept) => {
          arr.push({
            userId: dept.deptId.toString(),
            userImage: "../../static/dept.png",
            userName: dept.deptName,
            type: "department",
            checked: true,
            nickName: item.nickName,
            parentUserId: this.loginInfo.parentUserId, // 父级授权人
            toPowerId: this.loginInfo.userId, //   授权对象
            powerModule: this.loginInfo.powerModule,
          });
        });
      }
      return arr;
    },
    // 格式转化
    __formatStaff(item) {
      let arr = [];
      if (item.toSysUsers && item.toSysUsers.length > 0) {
        item.toSysUsers.forEach((user) => {
          arr.push({
            userId: user.userName,
            userImage: user.avatar,
            userName: user.nickName,
            type: "employee",
            checked: true,
            nickName: item.nickName,
            parentUserId: this.loginInfo.parentUserId, // 父级授权人
            toPowerId: this.loginInfo.userId, //   授权对象
            powerModule: this.loginInfo.powerModule,
          });
        });
      }
      return arr;
    },
    toSave() {
      uni.showLoading({
        title: "保存中",
      });
      let powerDeptList = [];
      let powerUserList = [];
      this.authorities.forEach((item) => {
        if (item.type == "department") {
          if (item.hasOwnProperty("isActive")) {
            powerDeptList.push({
              powerModule: this.loginInfo.powerModule,
              parentUserId: this.loginInfo.parentUserId, // 父级授权人
              toPowerId: this.loginInfo.toPowerId, //   授权对象
              powerDeptId: item.userId,
              isActive: item.isActive ? "1" : "0",
            });
          } else {
            powerDeptList.push({
              powerModule: this.loginInfo.powerModule,
              parentUserId: this.loginInfo.parentUserId, // 父级授权人
              toPowerId: this.loginInfo.toPowerId, //   授权对象
              powerDeptId: item.userId,
            });
          }
        } else if (item.type == "employee") {
          if (item.hasOwnProperty("isActive")) {
            powerUserList.push({
              powerModule: this.loginInfo.powerModule,
              parentUserId: this.loginInfo.parentUserId, // 父级授权人
              toPowerId: this.loginInfo.toPowerId, //   授权对象
              powerUserId: item.userId, // 被授权的对象id（删除部门权限此项传空）
              isActive: item.isActive ? "1" : "0",
            });
          } else {
            powerUserList.push({
              powerModule: this.loginInfo.powerModule,
              parentUserId: this.loginInfo.parentUserId, // 父级授权人
              toPowerId: this.loginInfo.toPowerId, //   授权对象
              powerUserId: item.userId, // 被授权的对象id（删除部门权限此项传空）
            });
          }
        }
      });
      const data = {
        powerDeptList: powerDeptList,
        powerUserList: powerUserList,
      };

      savePower(
        data,
        (res) => {
          if (res && res.data && res.data.code == 200) {
            uni.showToast({
              type: "success",
              title: "保存成功",
              duration: 2000,
              mask: true,
            });

            setTimeout(() => {
              savePowerSource(
                { userNames: this.loginInfo.toPowerId },
                (res) => {
                  console.log(res.data);
                },
                (err) => {
                  console.log(err);
                }
              );

              let arr = [];
              if (res.data.dept && res.data.dept.length > 0) {
                let list = res.data.dept;
                if (list.length > 0) {
                  for (let i = 0; i < list.length; i++) {
                    arr = arr.concat(this.__format(list[i]));
                  }
                }
              }
              if (res.data.user && res.data.user.length > 0) {
                let list = res.data.user;
                if (list.length > 0) {
                  for (let i = 0; i < list.length; i++) {
                    arr = arr.concat(this.__formatStaff(list[i]));
                  }
                }
              }
              this.authorities = arr;

              this.isShowSaveBtn = false;
              this.callbackItems = [];
            }, 2000);
          } else {
            uni.showToast({
              title: "保存权限失败",
              duration: 2000,
            });
          }
        },
        (err) => {
          uni.showToast({
            title: "操作失败",
            duration: 2000,
          });
        }
      );
    },
  },
};
</script>

<style scoped>
.footer-remove-btn {
  font-weight: 500;
  color: #3875c6;
  font-size: 32upx;
  background: transparent;
}
.footer-remove-btn:after {
  border: none;
}
.footer-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  background: transparent;
}
.footer-mark {
  flex: 1;
  font-size: 26upx;
  color: #fd0043;
}
.to-add {
  width: 90%;
  line-height: 100rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: bold;
  color: #ffffff;
  background: #3875c6;
  border-radius: 6upx;
  margin: 30upx 0;
}
.null-content {
  height: 206upx;
}
</style>
